<?php
/**
 * XiaoYuanMenSuo-PHP
 * ==================================================================
 * CopyRight © 2017-2099 广州米袋软件有限公司
 * 官网地址：http://www.mdsoftware.cn
 * 售后技术支持：15017566075
 * ------------------------------------------------------------------
 * 这不是一个自由软件！未经本公司授权您只能在不用于商业目的的前提下
 * 对本程序代码进行修改和使用；不允许对本程序代码以任何目的的再发布。
 * ==================================================================
 *
 * @Author ZHC(codecookies@163.com)
 * @Date 2021-12-14 11:28 星期二
 * @Version 1.0
 */

namespace app\controller\api;


use app\common\service\sms\AliSms;
use app\middleware\AdminPermission;
use app\model\AdminStaff;
use app\model\AdminUser;
use app\model\AdminVisitRegistrationLog;
use app\common\service\wxapi\CheckIdCard;
use app\model\AdminVisitUser;
use app\util\ReturnCode;
use app\util\Tools;
use think\facade\Cache;
use think\facade\Validate;
use think\Response;

class Manager extends Base
{
    // 管理员、门卫来访登记列表
    public function logList(): Response
    {
        $data['api_auth'] = $this->request->header('Api-Auth');
        $data['page'] = $this->request->get('page', 1);
        $data['start_day'] = $this->request->get('start_day');
        $data['end_day'] = $this->request->get('end_day');
        $key_words = $this->request->get('key_words');
        $data['type'] = $this->request->get('type', 'admin');
        $validate = Validate::rule([
            'api_auth|登录token'=>'require',
            'page|分页'=>'require',
            'start_day|开始日期'=>'requireWith:end_day|before:end_day',
            'end_day|结束日期,' => 'requireWith:start_day|after:start_day',
            'type|类型' => 'require|in:admin,worker',
        ]);
        if (!$validate->check($data)) {
            return $this->buildFailed(ReturnCode::PARAM_INVALID, $validate->getError());
        }

        if ($data['type'] == 'admin'){
            $user = (new AdminUser())->where(['wx_api_token' => $data['api_auth']])->find();
        }else{
            $user = (new AdminStaff())->where(['wx_api_token' => $data['api_auth'], 'is_delete' => 0])->find();
        }
        if (!$user){
            return $this->buildFailed(ReturnCode::CACHE_READ_ERROR, '管理员/门卫不存在，请尝试重新登录');
        }
        if ($user->status != 1){
            return $this->buildFailed(ReturnCode::DATA_EXISTS, '管理员/门卫未审核/审核不通过');
        }
        $query_permission = true;
        if ($data['type'] == 'worker') {
            $permission = $user->permission;
            $query_permission = isset($permission['query']);
        }
        if (!$query_permission) {
            return $this->buildFailed(ReturnCode::AUTH_ERROR, '您没有查询权限，请联系管理员');
        }
        $school_id = $user->school_id;

        $query = (new AdminVisitRegistrationLog())->with('schoolData')
            ->where(['school_id' => $school_id, 'is_delete' => 0]);

        if ($data['start_day']){
            $query->where('visiting_time', '>=', strtotime(date('Y-m-d', strtotime($data['start_day']))));
        }
        if ($data['end_day']){
            $query->where('visiting_time','<=', strtotime($data['end_day']));
        }
        if ($key_words){
            $query->where(function ($query) use ($key_words){
                $query->whereOr('nickname', 'like', '%' . $key_words . '%')
                    ->whereOr('phone', 'like', '%' . $key_words . '%');
            });
        }
        $log_list = $query->order(['status' => 'ASC', 'id' => 'DESC'])->paginate(['list_rows'=> 10, 'page' => $data['page']])->toArray();
        if ($log_list['data']){
            foreach ($log_list['data'] as &$log){
                $log['visiting_time'] = date('Y-m-d H:i:s', $log['visiting_time']);
                unset($log['openid']);
            }
            unset($log);
        }
        return $this->buildSuccess([
            'list' => $log_list['data'],
            'per_page' => $log_list['per_page'],
            'current_page' => $log_list['current_page'],
            'last_page' => $log_list['last_page'],
        ], '成功');
    }

    // 管理员审核记录
    public function visitCheck() : Response
    {
        $data['api_auth'] = $this->request->header('Api-Auth');
        $data['visit_id'] = $this->request->post('visit_id');
        $data['status'] = $this->request->post('status');
        $data['reason'] = $this->request->post('reason');
        $data['type'] = $this->request->post('type', 'admin');
        $validate = Validate::rule([
            'api_auth|登录token'=>'require',
            'visit_id|来访登记ID'=>'require',
            'status|审核状态'=>'require|in:1,2',
            'reason|拒绝原因,' => 'requireIf:status,2',
            'type|类型' => 'require|in:admin,worker',
        ]);
        if (!$validate->check($data)) {
            return $this->buildFailed(ReturnCode::PARAM_INVALID, $validate->getError());
        }

        if ($data['type'] == 'admin') {
            $user = (new AdminUser())->where(['wx_api_token' => $data['api_auth']])->find();
        } else {
            $user = (new AdminStaff())->where(['wx_api_token' => $data['api_auth'], 'is_delete' => 0])->find();
        }

        if (!$user){
            return $this->buildFailed(ReturnCode::DATA_EXISTS, '管理员不存在，请尝试重新登录');
        }
        if ($user->status != 1){
            return $this->buildFailed(ReturnCode::DATA_EXISTS, '管理员未审核/审核不通过');
        }
        if ($data['type'] == 'admin') {
            $permission = new AdminPermission();
            $audit_permission = $permission->checkAuth($user->id, 'api/Manager/visitCheck');
        } else {
            $audit_permission = isset($permission['audit']);
        }
        if (!$audit_permission) {
            return $this->buildFailed(ReturnCode::AUTH_ERROR, '审批权限验证失败，请联系管理员');
        }

        $log = (new AdminVisitRegistrationLog())->with(['schoolData','pictureData'])
            ->where(['id' => $data['visit_id'], 'school_id' => $user->school_id, 'is_delete' => 0, 'status' => 0])
            ->find();
        if (!$log){
            return $this->buildFailed(ReturnCode::DATA_EXISTS, '数据不存在');
        }

        $log->status = $data['status'];
        $log->refuse_reason = $data['reason'] && $data['status'] == 2 ? $data['reason'] : '';
        if (!$log->save()){
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
        }else{
            return $this->buildSuccess( [],'成功');
        }
    }

    // 管理员、门卫 —— 我的
    public function personalCenter() : Response
    {
        $api_auth = $this->request->header('Api-Auth');
        $type = $this->request->get('type');
        if (!$api_auth || !$type){
            return $this->buildFailed(ReturnCode::PARAM_INVALID, '缺少参数');
        }

        if ($type == 'admin'){
            $user = (new AdminUser())->where(['wx_api_token' => $api_auth])->find();
        }else{
            $user = (new AdminStaff())->where(['wx_api_token' => $api_auth, 'is_delete' => 0])->find();
        }

        if (!$user){
            return $this->buildFailed(ReturnCode::DATA_EXISTS, '管理员/门卫不存在，请尝试重新登录');
        }
        if ($user->status != 1){
            return $this->buildFailed(ReturnCode::DATA_EXISTS, '管理员/门卫未审核/审核不通过');
        }
        unset($user->password);
        $userInfo = $user->toArray();

        $userInfo['query_permission'] = true;
        $userInfo['audit_permission'] = false;
        if ($type == 'admin') {
            $permission = new AdminPermission();
            $userInfo['audit_permission'] = $permission->checkAuth($userInfo['id'], 'api/Manager/visitCheck');
        } else {
            unset($userInfo['permission']);
            $permission = $user->permission;
            $userInfo['query_permission'] = isset($permission['query']);
            $userInfo['audit_permission'] = isset($permission['audit']);
        }

        return $this->buildSuccess( ['user' => $userInfo],'成功');
    }

    //管理员、门卫 —— 修改个人资料
    public function personalUpdate() : Response
    {
        $api_auth = $this->request->header('Api-Auth');
        $type = $this->request->post('type');
        $name = $this->request->post('name');
        $sex = $this->request->post('sex');
        $id_card = $this->request->post('id_card');
        $avatar_url = $this->request->post('avatar_url');
        if (!$api_auth || !$type || !$name){
            return $this->buildFailed(ReturnCode::PARAM_INVALID, '缺少参数');
        }
        if ($type == 'worker' && (!$sex || !$id_card || !$avatar_url)){
            return $this->buildFailed(ReturnCode::PARAM_INVALID, '缺少参数');
        }
        //校验身份证
        if ($type == 'worker' && !CheckIdCard::check($id_card)){
            return $this->buildFailed(ReturnCode::PARAM_INVALID, '请填写正确的身份证信息');
        }

        if ($type == 'admin'){
            $user = (new AdminUser())->where(['wx_api_token' => $api_auth])->find();
        }else{
            $user = (new AdminStaff())->where(['wx_api_token' => $api_auth, 'is_delete' => 0])->find();
        }

        if (!$user){
            return $this->buildFailed(ReturnCode::DATA_EXISTS, '管理员/门卫不存在，请尝试重新登录');
        }
        if ($user->status != 1){
            return $this->buildFailed(ReturnCode::DATA_EXISTS, '管理员/门卫未审核/审核不通过');
        }

        if ($type == 'admin'){
            $user->nickname = $name;
            if (!$user->save()){
                return $this->buildFailed(ReturnCode::UPDATE_FAILED, '编辑失败');
            }
        }else{
            $user->name = $name;
            $user->sex = $sex;
            $user->id_card = $id_card;
            $user->avatar_url = $avatar_url;
            if (!$user->save()){
                return $this->buildFailed(ReturnCode::UPDATE_FAILED, '编辑失败');
            }
        }

        return $this->buildSuccess( [],'成功');
    }

    //管理员、门卫 —— 修改密码
    public function modifyPassword() : Response
    {
        $phone  = input('post.phone');
        $code  = input('post.code/d');
        $password  = input('post.password');
        $confirm  = input('post.password_confirm');
        $api_auth = $this->request->header('Api-Auth');
        $type = input('post.type'); // worker 门卫 admin 管理员
        if (!$api_auth || !$type){
            return $this->buildFailed(ReturnCode::PARAM_INVALID, '缺少参数');
        }

        if (empty($phone) || !validatePhone($phone)) {
            return $this->buildFailed(ReturnCode::PARAM_INVALID, '请输入正确的手机号');
        }
        if ($password != $confirm) {
            return $this->buildFailed(ReturnCode::NUMBER_MATCH_ERROR, '输入的新密码不一致');
        }
        if (!AliSms::check($phone, $code)) {
            return $this->buildFailed(ReturnCode::RECORD_NOT_FOUND, '验证码错误');
        }

        if ($type == 'admin'){
            $user = (new AdminUser())->where(['wx_api_token' => $api_auth, 'phone' => $phone, 'status' => 1])->find();
        }else{
            $user = (new AdminStaff())->where(['wx_api_token' => $api_auth, 'phone' => $phone, 'is_delete' => 0, 'status' => 1])->find();
        }
        if (!$user) {
            return $this->buildFailed(ReturnCode::RECORD_NOT_FOUND, '账号不存在, 请尝试重新登录');
        }
        $user->password = Tools::userMd5($password);
        $user->save();

        Cache::delete("code_cache".$phone);
        return $this->buildSuccess([], '密码修改成功');
    }

    //管理员、门卫 —— 修改手机
    public function changePhone() : Response
    {
        $api_auth = $this->request->header('Api-Auth');
        $type = $this->request->post('type');
        $old_phone = $this->request->post('old_phone');
        $new_phone = $this->request->post('new_phone');
        $old_captcha = $this->request->post('old_captcha');
        $new_captcha = $this->request->post('new_captcha');
        if (!$api_auth || !$type || !$old_phone || !$new_phone || !$old_captcha || !$new_captcha){
            return $this->buildFailed(ReturnCode::PARAM_INVALID, '缺少参数');
        }

        if (!validatePhone($old_phone) || !validatePhone($new_phone)) {
            return $this->buildFailed(ReturnCode::PARAM_INVALID, '请输入正确的手机号');
        }

        if (!AliSms::check($old_phone, intval($old_captcha)) || !AliSms::check($new_phone, intval($new_captcha))) {
            return $this->buildFailed(ReturnCode::RECORD_NOT_FOUND, '验证码错误');
        }

        if ($type == 'admin'){
            $user = (new AdminUser())->where(['wx_api_token' => $api_auth, 'phone' => $old_phone])->find();
        }else{
            $user = (new AdminStaff())->where(['wx_api_token' => $api_auth, 'is_delete' => 0, 'phone' => $old_phone])->find();
        }

        if (!$user){
            return $this->buildFailed(ReturnCode::DATA_EXISTS, '手机用户不存在，请尝试重新登录');
        }
        if ($user->status != 1){
            return $this->buildFailed(ReturnCode::DATA_EXISTS, '管理员/门卫未审核/审核不通过');
        }

        $user->phone = $new_phone;
        if (!$user->save()){
            return $this->buildFailed(ReturnCode::UPDATE_FAILED, '编辑失败');
        }

        return $this->buildSuccess( [],'成功');
    }
}